import { ref } from 'vue'

export interface VoiceRecognitionMessage {
  type: 'start' | 'stop' | 'select_device' | 'recognition_started' | 'recognition_stopped' | 'recognition_result' | 'device_selected' | 'error'
  data?: any
  text?: string
  confidence?: number
  success?: boolean
  error?: string
  deviceId?: string
}

export class VoiceWebSocketService {
  private ws: WebSocket | null = null
  private isConnected = ref(false)
  private isRecording = ref(false)
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectDelay = 1000

  // 回调函数
  private onMessageCallback: ((message: VoiceRecognitionMessage) => void) | null = null
  private onErrorCallback: ((error: string) => void) | null = null
  private onConnectCallback: (() => void) | null = null
  private onDisconnectCallback: (() => void) | null = null

  constructor(private baseUrl: string = '') {
    // 使用API域名而不是当前域名，因为WebSocket运行在API服务器上
    this.baseUrl = baseUrl || `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//api.mensanyun.com`
  }

  // 连接WebSocket
  connect(token?: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      try {
        const wsUrl = `${this.baseUrl}/ws/voice${token ? `?token=${token}` : ''}`
        console.log('连接WebSocket:', wsUrl)
        
        this.ws = new WebSocket(wsUrl)
        
        this.ws.onopen = () => {
          console.log('WebSocket连接成功')
          this.isConnected.value = true
          this.reconnectAttempts = 0
          this.onConnectCallback?.()
          resolve(true)
        }
        
        this.ws.onmessage = (event) => {
          try {
            const message: VoiceRecognitionMessage = JSON.parse(event.data)
            console.log('收到WebSocket消息:', message)
            this.onMessageCallback?.(message)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }
        
        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error)
          this.onErrorCallback?.('WebSocket连接错误')
          reject(new Error('WebSocket连接失败'))
        }
        
        this.ws.onclose = (event) => {
          console.log('WebSocket连接关闭:', event.code, event.reason)
          this.isConnected.value = false
          this.onDisconnectCallback?.()
          
          // 自动重连
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            setTimeout(() => {
              this.reconnectAttempts++
              console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
              this.connect(token)
            }, this.reconnectDelay * this.reconnectAttempts)
          }
        }
        
      } catch (error) {
        console.error('创建WebSocket失败:', error)
        reject(error)
      }
    })
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
      this.isConnected.value = false
    }
  }

  // 选择设备
  selectDevice(deviceId: string) {
    if (!this.isConnected.value) {
      throw new Error('WebSocket未连接')
    }
    
    const message: VoiceRecognitionMessage = {
      type: 'select_device',
      deviceId: deviceId
    }
    
    this.sendMessage(message)
  }

  // 开始语音识别
  startRecognition() {
    if (!this.isConnected.value) {
      throw new Error('WebSocket未连接')
    }
    
    const message: VoiceRecognitionMessage = {
      type: 'start'
    }
    
    this.sendMessage(message)
    this.isRecording.value = true
  }

  // 发送音频数据
  sendAudioData(audioData: Blob | ArrayBuffer) {
    if (!this.isConnected.value || !this.isRecording.value) {
      return
    }
    
    if (audioData instanceof Blob) {
      // 转换为ArrayBuffer
      audioData.arrayBuffer().then(buffer => {
        this.sendBinaryData(buffer)
      })
    } else {
      this.sendBinaryData(audioData)
    }
  }

  // 停止语音识别
  stopRecognition() {
    if (!this.isConnected.value) {
      return
    }
    
    const message: VoiceRecognitionMessage = {
      type: 'stop'
    }
    
    this.sendMessage(message)
    this.isRecording.value = false
  }

  // 发送文本消息
  private sendMessage(message: VoiceRecognitionMessage) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message))
    } else {
      console.error('WebSocket未连接，无法发送消息')
    }
  }

  // 发送二进制数据
  private sendBinaryData(data: ArrayBuffer) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(data)
    } else {
      console.error('WebSocket未连接，无法发送音频数据')
    }
  }

  // 设置回调函数
  onMessage(callback: (message: VoiceRecognitionMessage) => void) {
    this.onMessageCallback = callback
  }

  onError(callback: (error: string) => void) {
    this.onErrorCallback = callback
  }

  onConnect(callback: () => void) {
    this.onConnectCallback = callback
  }

  onDisconnect(callback: () => void) {
    this.onDisconnectCallback = callback
  }

  // 获取状态
  get isConnectedRef() {
    return this.isConnected
  }

  get isRecordingRef() {
    return this.isRecording
  }
}

// 创建全局实例
export const voiceWebSocket = new VoiceWebSocketService() 